package com.yuexia.yxim.server.handler;

import com.yuexia.yxim.common.bean.msg.ProtoMsg;
import com.yuexia.yxim.common.cocurrent.FutureTaskScheduler;
import com.yuexia.yxim.server.processer.ChatRedirectProcesser;
import com.yuexia.yxim.server.server.ServerSession;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: yue_xia
 * @Date: 2020/6/2 8:45 下午
 */
@Slf4j
@Service
@ChannelHandler.Sharable
public class ChatRedirectHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private ChatRedirectProcesser chatRedirectProcesser;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //判断消息实例
        if (msg == null || !(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }

        //判断消息类型
        ProtoMsg.Message pkg = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType pkgType = pkg.getType();

        if (!pkgType.equals(chatRedirectProcesser.type())) {
            super.channelRead(ctx, msg);
            return;
        }

        //判断是否登录
        ServerSession session = ServerSession.getSession(ctx);
        if (session == null || !session.isLogin()) {
            log.error("用户未登录 不能发送消息");
            return;
        }

        //异步处理im消息转发
        FutureTaskScheduler.add(() -> chatRedirectProcesser.action(session, pkg));

    }
}
